from DrissionPage import ChromiumPage, ChromiumOptions
import os


def get_url(url, num):
    co = ChromiumOptions().set_paths(browser_path=r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe") # 设置浏览器路径
    # co = ChromiumOptions()
    #
    # edge_path = r"D:\Microsoft\Edge\Application\msedge.exe"
    # if not os.path.exists(edge_path):
    #     print(f"错误：Edge 浏览器路径不存在：{edge_path}")
    #     return
    #
    # # ✅ 关键修正：在 set_paths() 里同时设置 user_data_path
    # co.set_paths(browser_path=edge_path, user_data_path=r"D:\Microsoft\EdgeUserData1")

    co.set_argument('--headless')

    page = ChromiumPage(co)
    page.get(url)



    page.wait(3)  # 等待页面加载完全
    page.run_js("window.scrollTo(0, 0);")  # 先滚动到顶部
    page.wait(1)
    urls = []
    # 滚动到底部
    for i in range(30):
        page.run_js("window.scrollBy(0,7000)")
        print(f"滚动{i+1}次")
        page.wait(1)



    first_element = page.ele('x://div[@id="contents"]')


    # 获取该元素中的所有次级元素
    if first_element:
        print(first_element)
        page.wait(10)
        links = first_element.eles('x://ytd-video-renderer[@class="style-scope ytd-item-section-renderer"]//a[@id="video-title"]')
        print(links)
        for i in links:
            try:
                # badge = i.ele('x://div[@class="badge  badge-style-type-simple style-scope ytd-badge-supported-renderer style-scope ytd-badge-supported-renderer"]')
                # if badge:  # 查找包含“字幕”的视频
                #     print(badge.ele('x://p').text)
                    # if badge.ele('x://p').text == '字幕':  # 判断是否含字幕

                href = i.attr('href')
                print(href)
                urls.append(href)

            except Exception as e:
                print("错误:", e)

    # urls 去重
    urls = list(set(urls))

    # 将urls写入文件
    with open(fr"D:\subtitle\bring_goods\{num}\urls.txt", 'w', encoding='utf-8') as file:
        for url in urls:
            file.write(url + '\n')  # 将每个 URL 写入文件，每行一个

    page.quit()
    print("已写入文件")

def get_subtitle(num):
    with open(fr"D:\subtitle\bring_goods\{num}\urls.txt", 'r', encoding='utf-8') as file:
        urls = [line.strip() for line in file]

    co1 = ChromiumOptions().set_paths(browser_path=r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe") # 设置浏览器路径
    co1.set_pref('download.default_directory', fr'D:\subtitle\bring_goods\{num}')  # 指定下载路径

    page1 = ChromiumPage(co1)  # 创建浏览器对象

    for href in urls:
        target = f'https://downsub.com/?url={href}'
        print(target)
        page1.get(target)

        button = page1.ele('x://button[@class="primary v-btn v-btn--depressed v-btn--rounded theme--light v-size--x-small"]')
        if button:
            button.click()
            print("搜寻字幕")


            try:
                # first_button = page1.ele('x://button[@class="download-button" and @data-title="[SRT] English (United States)"]')
                first_button = page1.ele('x://span[@class="v-btn__content"]')
                print(first_button)
                first_button.click()

                print("下载字幕")
                page1.wait(0.5)

            except Exception as e:
                pass


        else:
            print("未找到下载按钮")
    page1.quit()

url = "https://www.youtube.com/results?search_query=Dude+Perfect"
num = 76

# get_url(url, num)
get_subtitle(num)